﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web;
using X.Entity;
using System.Web.Caching;
using System.Web.UI.HtmlControls;
using System.IO;


namespace X.Web
{
    public class PageBase : Page
    {
        private static readonly object EventRefreshed = new object();

        public event EventHandler Refreshed
        {
            add { base.Events.AddHandler(EventRefreshed, value); }
            remove { base.Events.RemoveHandler(EventRefreshed, value); }
        }

        public virtual bool IsCheckRefreshed
        {
            get { return false; }
        }

        public static bool IsRefreshed
        {
            get
            {
                object obj = HttpContext.Current.Items["IsRefreshed"];
                if (null == obj)
                    return false;
                return (bool)obj;
            }
        }

        public SiteInfo SiteInfoConfig
        {
            get
            {
                SiteInfo instance = (SiteInfo)Cache[X.Common.XConst.CACHE_SiteInfo];

                if (null == instance || instance.IsNull)
                    instance = Bll.Params.GetSiteInfo();

                return instance;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //Title
            Title += string.Format(" {0} - {1}", X.Common.StringUtils.HtmlDecode(SiteInfoConfig.SiteTitle), X.Common.StringUtils.HtmlDecode(SiteInfoConfig.SiteName));

            //Keywords
            //HtmlMeta keywords = new HtmlMeta();
            //keywords.Name = "keywords";
            //keywords.Content = SiteInfoConfig.SiteKeyword;
            //Header.Controls.Add(keywords);

            ////Description
            //HtmlMeta description = new HtmlMeta();
            //description.Name = "description";
            //description.Content = SiteInfoConfig.SiteDescription;
            //Header.Controls.Add(description);
        }

        protected override void OnError(EventArgs e)
        {
            string filePath = Server.MapPath(string.Format("/Log/{0}.log", DateTime.Now.ToString("yyyyMMddHHmmss")));

            Exception ex = Server.GetLastError().GetBaseException();

            StringBuilder strBuilder = new StringBuilder();
            strBuilder.AppendLine("Message:");
            strBuilder.Append(ex.Message);
            strBuilder.AppendLine("StrackTrace:");
            strBuilder.Append(ex.StackTrace);
            strBuilder.AppendLine("TargetSite:");
            strBuilder.Append(ex.TargetSite.Name);
            strBuilder.AppendLine("DeclaringType:");
            strBuilder.Append(ex.TargetSite.DeclaringType.FullName);

            File.AppendAllText(filePath, strBuilder.ToString(), Encoding.Default);

            base.OnError(e);
        }
    }
}
